<?php

namespace app\common\service;

use think\Exception;

/**
 * Scanwork应用云存储服务类
 */
class ScanworkCloudService
{
    protected $config;
    protected $uploadService;
    
    public function __construct($configId = null)
    {
        error_log('ScanworkCloudService - 开始构造');
        
        // 如果没有指定配置ID，使用默认配置
        if (!$configId) {
            error_log('ScanworkCloudService - 未指定配置ID，获取默认配置');
            $config = \app\admin\model\yuncunchu\Config::getDefaultConfig();
            if (!$config) {
                error_log('ScanworkCloudService - 未找到可用的云存储配置');
                throw new Exception('未找到可用的云存储配置');
            }
            $configId = $config->id;
            error_log('ScanworkCloudService - 使用默认配置ID: ' . $configId);
        }
        
        error_log('ScanworkCloudService - 查找配置ID: ' . $configId);
        $this->config = \app\admin\model\yuncunchu\Config::find($configId);
        if (!$this->config) {
            error_log('ScanworkCloudService - 云存储配置不存在');
            throw new Exception('云存储配置不存在');
        }
        
        if ($this->config->status != 1) {
            error_log('ScanworkCloudService - 云存储配置已禁用');
            throw new Exception('云存储配置已禁用');
        }
        
        error_log('ScanworkCloudService - 创建YuncunchuService');
        $this->uploadService = new YuncunchuService($configId);
        error_log('ScanworkCloudService - 构造完成');
    }
    
    /**
     * 上传报工图片
     */
    public function uploadReportImage($file, $module = 'scanwork', $action = 'report')
    {
        return $this->uploadImage($file, $module, $action);
    }
    
    /**
     * 上传审核图片
     */
    public function uploadAuditImage($file, $module = 'scanwork', $action = 'audit')
    {
        return $this->uploadImage($file, $module, $action);
    }
    
    /**
     * 上传主动报工图片
     */
    public function uploadActiveReportImage($file, $module = 'scanwork', $action = 'active_report')
    {
        return $this->uploadImage($file, $module, $action);
    }
    
    /**
     * 上传产品图片
     */
    public function uploadProductImage($file, $module = 'scanwork', $action = 'product')
    {
        return $this->uploadImage($file, $module, $action);
    }
    
    /**
     * 上传审核视频
     */
    public function uploadAuditVideo($file, $module = 'scanwork', $action = 'audit_video')
    {
        return $this->uploadVideo($file, $module, $action);
    }
    
    /**
     * 通用图片上传方法
     */
    protected function uploadImage($file, $module, $action)
    {
        try {
            \think\Log::info('ScanworkCloudService - uploadImage方法被调用');
            // 验证文件
            $this->validateFile($file);
            \think\Log::info('ScanworkCloudService - 文件验证通过');
            
            // 直接调用云存储上传控制器的方法
            \think\Log::info('ScanworkCloudService - 开始创建Upload控制器');
            $uploadController = new \app\admin\controller\yuncunchu\Upload();
            \think\Log::info('ScanworkCloudService - Upload控制器创建完成');
            
            // 调用上传方法
            $result = $uploadController->uploadFile($file, $this->config->id, $module, $action);
            
            if ($result['success']) {
                return [
                    'success' => true,
                    'url' => $result['file_url'],
                    'file_id' => $result['file_id'],
                    'file_name' => $result['file_name'],
                    'file_size' => $result['file_size']
                ];
            } else {
                throw new Exception($result['message']);
            }
        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }
    
    /**
     * 通用视频上传方法
     */
    protected function uploadVideo($file, $module, $action)
    {
        try {
            // 验证视频文件
            $this->validateVideoFile($file);
            
            // 直接调用云存储上传控制器的方法
            $uploadController = new \app\admin\controller\yuncunchu\Upload();
            
            // 调用上传方法
            $result = $uploadController->uploadFile($file, $this->config->id, $module, $action);
            
            if ($result['success']) {
                return [
                    'success' => true,
                    'url' => $result['file_url'],
                    'file_id' => $result['file_id'],
                    'file_name' => $result['file_name'],
                    'file_size' => $result['file_size']
                ];
            } else {
                throw new Exception($result['message']);
            }
        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }
    
    /**
     * 验证文件
     */
    protected function validateFile($file)
    {
        if (!$file) {
            throw new Exception('没有接收到文件');
        }
        
        // 检查文件大小（最大10MB）
        $maxSize = 10 * 1024 * 1024;
        if ($file['size'] > $maxSize) {
            throw new Exception('文件大小超过限制（最大允许：10MB）');
        }
        
        // 检查文件类型
        $allowedTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
        $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($extension, $allowedTypes)) {
            throw new Exception('不支持的文件类型：' . $extension);
        }
        
        // 检查文件是否上传成功
        if ($file['error'] !== UPLOAD_ERR_OK) {
            throw new Exception('文件上传失败');
        }
    }
    
    /**
     * 验证视频文件
     */
    protected function validateVideoFile($file)
    {
        if (!$file) {
            throw new Exception('没有接收到文件');
        }
        
        // 检查文件大小（最大100MB）
        $maxSize = 100 * 1024 * 1024;
        if ($file['size'] > $maxSize) {
            throw new Exception('视频文件过大，请上传小于100MB的视频');
        }
        
        // 检查文件类型
        $allowedTypes = ['mp4', 'avi', 'mov', 'wmv', 'flv', '3gp', 'webm'];
        $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($extension, $allowedTypes)) {
            throw new Exception('不支持的视频格式，请上传MP4、AVI、MOV、WMV、FLV、3GP或WEBM格式的视频');
        }
        
        // 检查文件是否上传成功
        if ($file['error'] !== UPLOAD_ERR_OK) {
            throw new Exception('文件上传失败');
        }
    }
    
    /**
     * 删除文件
     */
    public function deleteFile($fileId, $fileUrl = null)
    {
        try {
            if ($fileId) {
                $result = $this->uploadService->delete($fileId);
            } elseif ($fileUrl) {
                // 根据URL删除文件
                $result = $this->uploadService->deleteByUrl($fileUrl);
            } else {
                throw new Exception('缺少文件ID或文件URL');
            }
            
            return [
                'success' => true,
                'message' => '删除成功'
            ];
        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * 测试连接
     */
    public function testConnection()
    {
        try {
            $result = $this->uploadService->test();
            return [
                'success' => true,
                'data' => $result
            ];
        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }
    
    /**
     * 获取文件信息
     */
    public function getFileInfo($fileId)
    {
        try {
            $file = \app\admin\model\yuncunchu\File::find($fileId);
            if (!$file) {
                throw new Exception('文件不存在');
            }
            
            return [
                'success' => true,
                'file' => $file
            ];
        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }
    
    /**
     * 批量上传图片
     */
    public function batchUploadImages($files, $module = 'scanwork', $action = 'batch')
    {
        $results = [];
        $successCount = 0;
        $failedCount = 0;
        
        foreach ($files as $file) {
            $result = $this->uploadImage($file, $module, $action);
            if ($result['success']) {
                $successCount++;
            } else {
                $failedCount++;
            }
            $results[] = $result;
        }
        
        return [
            'success' => true,
            'results' => $results,
            'success_count' => $successCount,
            'failed_count' => $failedCount
        ];
    }
}
